#include "UserManager.h"
#include "Database.h"
#include <openssl/sha.h>
std::string sha256(const std::string& str) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    
    std::stringstream ss;
    for(unsigned char i : hash) {
        ss << std::hex << std::setw(2) << std::setfill('0') << (int)i;
    }
    return ss.str();
}
Session UserManager::login(const std::string& username, const std::string& password) {
    std::lock_guard<std::mutex> lock(dbMutex);
    
    // 密码加密验证
    const std::string hashedPwd = sha256(password);
    
    sqlite3_stmt* stmt;
    const char* query = "SELECT id, role FROM users WHERE username=? AND password_hash=?";
    
    if(sqlite3_prepare_v2(Database::getInstance().getHandle(), query, -1, &stmt, nullptr) != SQLITE_OK) {
        throw std::runtime_error("Database prepare error");
    }
    
    sqlite3_bind_text(stmt, 1, username.c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, hashedPwd.c_str(), -1, SQLITE_STATIC);
    
    if(sqlite3_step(stmt) == SQLITE_ROW) {
        Session session;
        session.userId = sqlite3_column_int(stmt, 0);
        session.role = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
        session.token = generateSessionToken();
        activeSessions[session.token] = session;
        return session;
    }
    
    sqlite3_finalize(stmt);
    throw AuthException("Invalid credentials");
}
bool UserManager::checkPermission(const std::string& token, Permission required) {
    if(!activeSessions.count(token)) return false;
    
    const Session& session = activeSessions[token];
    if(session.role == "admin") return true;
    
    // 普通用户权限验证逻辑
    switch(required) {
        case Permission::DEVICE_CONTROL: 
            return checkDeviceAccess(session.userId, targetDevice);
        case Permission::LOG_VIEW:
            return false; // 示例限制
        // 其他权限判断...
    }
    return false;
}